package com.twq.TestThread;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.net.URL;
import java.util.concurrent.*;

/**
 * @author twq
 * @date 2021/8/20 16:51
 */
//1】创建Callable接口的实现类，并实现call()方法，然后创建该实现类的实例（从java8开始可以直接使用Lambda表达式创建Callable对象）。
//
//        2】使用FutureTask类来包装Callable对象，该FutureTask对象封装了Callable对象的call()方法的返回值
//
//        3】使用FutureTask对象作为Thread对象的target创建并启动线程（因为FutureTask实现了Runnable接口）
//
//        4】调用FutureTask对象的get()方法来获得子线程执行结束后的返回值

//可以定义返回值，可以抛出异常
public class TestCallable implements Callable<Boolean> {

    private  String url;
    private  String name;

    public TestCallable(String url, String name){
        this.name = name;
        this.url = url;
    }

    //下载图片的执行体
    @Override
    public Boolean call(){
        WebDownloader webDownloader = new WebDownloader();
        webDownloader.downloader(url,name);
        System.out.println("下载文件名为"+name);
        return true;
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        TestCallable t1 = new TestCallable("https://img11.51tietu.net/pic/2016-071418/20160714181543xyu10ukncwf221991.jpg","11.jpg");

        TestCallable t2 = new TestCallable("https://img1.baidu.com/it/u=3886212450,854269223&fm=26&fmt=auto&gp=0.jpg","21.jpg");

        TestCallable t3 = new TestCallable("https://img1.baidu.com/it/u=3886212450,854269223&fm=26&fmt=auto&gp=0.jpg","31.jpg");

        //创建执行服务
        ExecutorService ser = Executors.newFixedThreadPool(3);

//        提交执行
        Future<Boolean> r1 = ser.submit(t1);
        Future<Boolean> r2 = ser.submit(t2);
        Future<Boolean> r3 = ser.submit(t3);

//        获取结果
        Boolean rs1 = r1.get();
        Boolean rs2 = r2.get();
        Boolean rs3 = r3.get();

//        关闭服务
        ser.shutdownNow();
    }


    //下载器
    class WebDownloader{
        //下载方法
        public  void downloader(String url,String name){
            try {
                FileUtils.copyURLToFile(new URL(url),new File(name));
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("io异常，download方法出现问题");
            }

        }
    }
}
